<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="分类名称:">
        <el-input v-model.trim="query.categoryName" placeholder="分类名称"></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.status" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="1" label="禁用">禁用</el-option>
          <el-option value="0" label="正常">正常</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="fetchCategoryList">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()" style="margin-bottom: 20px;">添加</el-button>
    <el-button size="small" type="danger" icon="el-icon-document-delete" @click="handleMultiDel()" style="margin-bottom: 20px;">删除</el-button>

    <!--  列表数据  -->
    <el-table :data="list" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange" tooltip-effect="dark">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" label="序号" width="80" type="index"></el-table-column>
      <el-table-column align="center" prop="cover" label="背景图" width="120">
        <template slot-scope="scope">
          <el-image :src="scope.row.cover" style="height: 40px;width: 40px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="categoryName" label="分类名称" width="300" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="categoryCode" label="分类代码" width="180" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 2" type="danger">禁用</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="操作" >
        <template slot-scope="scope">
          <el-button icon="el-icon-collection-tag"
                     type="primary" size="mini"
                     v-if="scope.row.status === 1"
                     @click="handleLabel(scope.row.categoryId)">分配标签</el-button>
          <el-button icon="el-icon-edit"
                     type="success" size="mini"
                     @click="handleEdit(scope.row.categoryId)">编辑</el-button>
          <el-button icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.categoryId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.pageNo"
                     :page-sizes="[10, 20, 50]"
                     :page-size="query.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="query.total">
      </el-pagination>
    </div>

    <el-dialog
      title="分配标签"
      :visible.sync="handleLabelVisible"
      width="35%"
      :before-close="handleCloseLabel">
        <div >
          <el-transfer :titles="['可选标签', '已选标签']"
                       v-model="labelIds"
                       :data="labelList"
                       :props="{key: 'labelId', label: 'labelName'}"></el-transfer>
        </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseLabel">取 消</el-button>
        <el-button type="primary" @click="submitHandleLabel">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer :title="title" :visible.sync="drawer" direction="rtl" :before-close="handleClose" :wrapper-closable="false">
      <el-form :model="category" ref="formData" label-width="120px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="分类名称：" prop="categoryName">
          <el-input v-model="category.categoryName" placeholder="请输入分类名称" show-word-limit maxlength="20" clearable/>
        </el-form-item>
        <el-form-item label="分类代码：" prop="categoryCode">
          <el-input v-model="category.categoryCode" placeholder="请输入分类代码" show-word-limit maxlength="20" clearable/>
        </el-form-item>
        <el-form-item label="背景图：" prop="cover" >
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadCover">
            <img v-if="category.cover" :src="category.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类状态：" prop="status" v-if="title === '编辑分类'">
          <el-radio-group v-model="category.status">
            <el-radio :label = 2 border>禁用</el-radio>
            <el-radio :label = 1 border>正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="danger" plain @click="handleClose">取消</el-button>
        <el-button size="small" type="success" @click="submit()" :loading="loading">提交</el-button>
      </el-row>
    </el-drawer>

  </div>
</template>
<script>
import { listCategory, deleteCategory, info, createCategory, editCategory, saveCategoryLabel } from "@/api/category";
import { dateFormat } from '@/utils/date';
import { getUserRole } from "@/utils/userToken";
import { listByCategoryId, allLabel } from "@/api/label"
import { uploadFile } from "@/api/file";
import {CATEGORY_COVER} from "@/utils/fileType";

export default {
  data() {
    return {
      query: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      list: [],
      checkedCategories: [],
      checkedCategoryIds: [],
      drawer: false,
      title: "添加分类",
      category: {
        categoryName: '',
        cover: '',
        categoryCode: ''
      },
      loading: false,
      valid: true,
      roleCode: '',
      handleLabelVisible: false,
      labelList: [],
      labelIds: [""],
      checkCategoryId: "",
    }
  },

  created() {
    this.fetchCategoryList();
    this.getRole();
  },

  methods: {
    // 查询分类列表
    fetchCategoryList() {
      listCategory(this.query).then(res => {
        if (res.code === 200) {
          this.list = res.data.list;
          this.query.total = res.data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    uploadCover(file) {
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', CATEGORY_COVER);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          this.category.cover = response.data;
          this.fetchCategoryList();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    handleCloseLabel() {
      this.labelList = [];
      this.labelIds = [];
      this.handleLabelVisible = false;
      this.checkCategoryId = "";
    },

    // 提交分配好的标签
    submitHandleLabel() {
      console.log("this.labelIds ==", this.labelIds)
      if (this.labelIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少分配一个标签',
          duration: 1500
        });
        return
      }

      const data = {
        categoryId: this.checkCategoryId,
        labelIds: this.labelIds
      }

      saveCategoryLabel(data).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '标签分配成功',
            type: 'success',
            duration: 1500
          });
          this.handleCloseLabel()
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 分配标签
    handleLabel(categoryId) {
      allLabel().then(res => {
        if (res.code === 200) {
          this.labelList = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })

      listByCategoryId(categoryId).then(res => {
        if (res.code === 200) {
          let len = [];
          this.labelIds = [];
          len = JSON.parse(JSON.stringify(res.data))
          if (len.length !== 0) {
            for (let i = 0; i < len.length; i++) {
              this.labelIds.push(len[i].labelId)
            }
          } else {
            this.labelIds = len;
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      })

      this.checkCategoryId = categoryId;
      this.handleLabelVisible = true;

    },

    // 删除
    handleDel(id) {
      this.$confirm('确认删除这条记录吗?删除后，该分类下的标签均被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          ids: []
        }
        data.ids.push(id)
        deleteCategory(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchCategoryList();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 批量删除
    handleMultiDel() {
      if (this.checkedCategoryIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个分类',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这条记录吗?删除后，该分类下的标签均被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          ids: []
        }
        data.ids = this.checkedCategoryIds;
        deleteCategory(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchCategoryList();
          this.checkedCategoryIds = []
        })
      }).catch(() => {
        // 取消删除
        this.checkedCategoryIds = []
      });
    },

    // 编辑
    handleEdit(id) {
      this.title = "编辑分类"
      this.drawer = true;

      info(id).then(res => {
        if (res.code === 200) {
          this.category = res.data
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 新增分类
    handleAdd() {
      this.drawer = true;
    },

    // 获取当前登录用户的角色
    getRole() {
      this.roleCode = getUserRole();
    },

    // 重置
    reload() {
      this.query.categoryName = '';
      this.query.scope = '';
      this.query.status = '';
      this.fetchCategoryList();
    },

    handleSelectionChange(val) {
      let len = JSON.parse(JSON.stringify(val))
      this.checkedCategoryIds = [];
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedCategoryIds.push(len[i].categoryId)
        }
      } else {
        this.checkedCategoryIds = len
      }
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // 关闭弹框
    handleClose(done) {
      this.drawer = false;
      this.title = "添加分类"
      this.category = {}
      this.fetchCategoryList();
    },


    // 提交
    submit() {
      this.loading = true;
      this.beforeSubAndEdit();
      if (!this.valid) {
        this.valid = true;
        this.loading = false;
        return;
      }

      if (this.title === '添加分类') {
        // 添加
        createCategory(this.category).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '分类添加成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
          }
        })
        this.valid = true;
        this.loading = false;
      } else {
        editCategory(this.category).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '分类编辑成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
          }
        })
        // 编辑
        this.valid = true;
        this.loading = false;
      }
    },

    beforeSubAndEdit() {
      if (!this.category.categoryName) {
        this.$notify.error({
          title: '错误',
          message: '请输入分类名称',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.category.categoryCode) {
        this.$notify.error({
          title: '错误',
          message: '请输入分类代码',
          duration: 1500
        });
        this.valid = false
      }

    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchCategoryList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchCategoryList();
    },


  }
}
</script>



<style>

</style>
